import { Card, Table, Select, Button, Space, Statistic, Row, Col, Tabs, Modal, Form, Input, InputNumber } from '@/utils/antd-imports';
import { PieChartOutlined, DownloadOutlined, CheckOutlined, CloseOutlined } from '@/utils/icons';
import { useState, useEffect } from 'react';


import DatePicker from 'antd/es/date-picker';








const { RangePicker } = DatePicker;
const { Option } = Select;
const { TabPane } = Tabs;

// 模拟产值数据
const outputData = [
  { 
    id: 1, 
    serialNumber: 1,
    employeeId: 'E0001',
    name: '张三',
    employeeType: '正式员工',
    projectName: '凯泽利总部大楼',
    accountPeriod: '2024-01',
    projectCode: 'P2023001',
    projectManager: '李经理',
    department: '设计部',
    projectLocation: '北京',
    joinDate: '2023-01-01',
    projectJoinDate: '2023-01-15',
    projectLeaveDate: '2023-12-31',
    resignationDate: '',
    businessType: '设计',
    hasOrder: true,
    unitPriceWithTax: 200,
    workHours: 160,
    deduction: 1000,
    monthlyOutput: 31000,
    monthlyOutputNoTax: 27900,
    salaryCost: 9300,
    socialInsurance: 3100,
    otherFees: 1550,
    commercialInsurance: 620,
    equipmentCost: 2480,
    compensationAmount: 310,
    totalCost: 16360,
    costRate: 52.77,
    remarks: '有订单项目',
    approvalStatus: 'approved' // approved, pending
  },
  { 
    id: 2, 
    serialNumber: 2,
    employeeId: 'E0002',
    name: '李四',
    employeeType: '外协人员',
    projectName: '未来科技园',
    accountPeriod: '2024-01',
    projectCode: 'P2023002',
    projectManager: '王经理',
    department: '工程部',
    projectLocation: '上海',
    joinDate: '2023-02-01',
    projectJoinDate: '2023-02-15',
    projectLeaveDate: '2023-11-30',
    resignationDate: '',
    businessType: '施工',
    hasOrder: false,
    unitPriceWithTax: 150,
    workHours: 140,
    deduction: 800,
    monthlyOutput: 20200,
    monthlyOutputNoTax: 18180,
    salaryCost: 6060,
    socialInsurance: 2020,
    otherFees: 1010,
    commercialInsurance: 404,
    equipmentCost: 1616,
    compensationAmount: 202,
    totalCost: 11312,
    costRate: 56.00,
    remarks: '无订单项目',
    approvalStatus: 'pending'
  },
  { 
    id: 3, 
    serialNumber: 3,
    employeeId: 'E0003',
    name: '王五',
    employeeType: '公司自由人',
    projectName: '城市综合体',
    accountPeriod: '2024-01',
    projectCode: 'P2023003',
    projectManager: '赵经理',
    department: '监理部',
    projectLocation: '广州',
    joinDate: '2023-03-01',
    projectJoinDate: '2023-03-15',
    projectLeaveDate: '2023-10-31',
    resignationDate: '',
    businessType: '监理',
    hasOrder: true,
    unitPriceWithTax: 180,
    workHours: 120,
    deduction: 600,
    monthlyOutput: 21000,
    monthlyOutputNoTax: 18900,
    salaryCost: 6300,
    socialInsurance: 2100,
    otherFees: 1050,
    commercialInsurance: 420,
    equipmentCost: 1680,
    compensationAmount: 210,
    totalCost: 11760,
    costRate: 56.00,
    remarks: '有订单项目',
    approvalStatus: 'approved'
  }
];

export default function OutputStatistics() {
  const [loading, setLoading] = useState(false);
  const [timeRange, setTimeRange] = useState([]);
  const [projectFilter, setProjectFilter] = useState('all');
  const [activeTab, setActiveTab] = useState('approved');
  const [approvalModalVisible, setApprovalModalVisible] = useState(false);
  const [currentRecord, setCurrentRecord] = useState(null);
  const [form] = Form.useForm();
  
  // 筛选数据
  const approvedData = outputData.filter(item => item.approvalStatus === 'approved');
  const pendingData = outputData.filter(item => item.approvalStatus === 'pending');
  
  const columns = [
    {
      title: '序号',
      dataIndex: 'serialNumber',
      key: 'serialNumber',
      width: 80,
      fixed: 'left'
    },
    {
      title: '工号',
      dataIndex: 'employeeId',
      key: 'employeeId',
      width: 100,
      fixed: 'left'
    },
    {
      title: '姓名',
      dataIndex: 'name',
      key: 'name',
      width: 100,
      fixed: 'left'
    },
    {
      title: '员工类型',
      dataIndex: 'employeeType',
      key: 'employeeType',
      width: 120
    },
    {
      title: '项目名称',
      dataIndex: 'projectName',
      key: 'projectName',
      width: 200
    },
    {
      title: '账期',
      dataIndex: 'accountPeriod',
      key: 'accountPeriod',
      width: 100
    },
    {
      title: '项目编号',
      dataIndex: 'projectCode',
      key: 'projectCode',
      width: 120
    },
    {
      title: '项目经理',
      dataIndex: 'projectManager',
      key: 'projectManager',
      width: 120
    },
    {
      title: '部门',
      dataIndex: 'department',
      key: 'department',
      width: 120
    },
    {
      title: '项目地',
      dataIndex: 'projectLocation',
      key: 'projectLocation',
      width: 100
    },
    {
      title: '入职时间',
      dataIndex: 'joinDate',
      key: 'joinDate',
      width: 120
    },
    {
      title: '入项时间',
      dataIndex: 'projectJoinDate',
      key: 'projectJoinDate',
      width: 120
    },
    {
      title: '离项时间',
      dataIndex: 'projectLeaveDate',
      key: 'projectLeaveDate',
      width: 120
    },
    {
      title: '离职时间',
      dataIndex: 'resignationDate',
      key: 'resignationDate',
      width: 120
    },
    {
      title: '业务类型',
      dataIndex: 'businessType',
      key: 'businessType',
      width: 100
    },
    {
      title: '是否有订单',
      dataIndex: 'hasOrder',
      key: 'hasOrder',
      width: 120,
      render: (hasOrder) => (
        hasOrder ? 
        <span style={{ color: '#52c41a' }}><CheckOutlined /> 有订单</span> : 
        <span style={{ color: '#ff4d4f' }}><CloseOutlined /> 无订单</span>
      )
    },
    {
      title: '单价（含税）',
      dataIndex: 'unitPriceWithTax',
      key: 'unitPriceWithTax',
      width: 120,
      render: value => `¥${value.toLocaleString()}`
    },
    {
      title: '工作时长',
      dataIndex: 'workHours',
      key: 'workHours',
      width: 100,
      render: value => `${value}h`
    },
    {
      title: '扣减',
      dataIndex: 'deduction',
      key: 'deduction',
      width: 100,
      render: value => `¥${value.toLocaleString()}`
    },
    {
      title: '当月产值',
      dataIndex: 'monthlyOutput',
      key: 'monthlyOutput',
      width: 120,
      render: value => <span style={{ fontWeight: 'bold' }}>¥{value.toLocaleString()}</span>
    },
    {
      title: '当月产值（不含税）',
      dataIndex: 'monthlyOutputNoTax',
      key: 'monthlyOutputNoTax',
      width: 150,
      render: value => `¥${value.toLocaleString()}`
    },
    {
      title: '工资成本',
      dataIndex: 'salaryCost',
      key: 'salaryCost',
      width: 120,
      render: value => `¥${value.toLocaleString()}`
    },
    {
      title: '企业社保公积金',
      dataIndex: 'socialInsurance',
      key: 'socialInsurance',
      width: 150,
      render: value => `¥${value.toLocaleString()}`
    },
    {
      title: '其他费用',
      dataIndex: 'otherFees',
      key: 'otherFees',
      width: 120,
      render: value => `¥${value.toLocaleString()}`
    },
    {
      title: '商保',
      dataIndex: 'commercialInsurance',
      key: 'commercialInsurance',
      width: 100,
      render: value => `¥${value.toLocaleString()}`
    },
    {
      title: '设备费用',
      dataIndex: 'equipmentCost',
      key: 'equipmentCost',
      width: 120,
      render: value => `¥${value.toLocaleString()}`
    },
    {
      title: '赔偿金额',
      dataIndex: 'compensationAmount',
      key: 'compensationAmount',
      width: 120,
      render: value => `¥${value.toLocaleString()}`
    },
    {
      title: '综合成本',
      dataIndex: 'totalCost',
      key: 'totalCost',
      width: 120,
      render: value => <span style={{ fontWeight: 'bold' }}>¥{value.toLocaleString()}</span>
    },
    {
      title: '单人成本率',
      dataIndex: 'costRate',
      key: 'costRate',
      width: 120,
      render: value => `${value}%`
    },
    {
      title: '备注',
      dataIndex: 'remarks',
      key: 'remarks',
      width: 150
    },
    {
      title: '操作',
      key: 'action',
      width: 100,
      fixed: 'right',
      render: (_, record) => (
        record.approvalStatus === 'pending' ? (
          <Button 
            type="primary" 
            size="small"
            onClick={() => handleApproval(record)}
          >
            批准
          </Button>
        ) : (
          <span style={{ color: '#52c41a' }}>已批准</span>
        )
      )
    }
  ];

  const handleSearch = () => {
    setLoading(true);
    // 模拟API调用
    setTimeout(() => {
      setLoading(false);
    }, 500);
  };

  const handleApproval = (record) => {
    setCurrentRecord(record);
    form.setFieldsValue({
      salaryCost: record.salaryCost,
      socialInsurance: record.socialInsurance,
      otherFees: record.otherFees,
      commercialInsurance: record.commercialInsurance,
      equipmentCost: record.equipmentCost,
      compensationAmount: record.compensationAmount,
      remarks: record.remarks
    });
    setApprovalModalVisible(true);
  };

  const handleApprovalSubmit = () => {
    form.validateFields().then(values => {
      setLoading(true);
      // 模拟API调用
      setTimeout(() => {
        setLoading(false);
        setApprovalModalVisible(false);
        // 这里应该更新数据状态
        console.log('批准数据:', values);
      }, 500);
    });
  };

  const currentData = activeTab === 'approved' ? approvedData : pendingData;
  const totalOutput = currentData.reduce((sum, item) => sum + item.monthlyOutput, 0);
  const totalOutputNoTax = currentData.reduce((sum, item) => sum + item.monthlyOutputNoTax, 0);
  const totalCost = currentData.reduce((sum, item) => sum + item.totalCost, 0);
  const avgCostRate = currentData.length > 0 ? 
    currentData.reduce((sum, item) => sum + item.costRate, 0) / currentData.length : 0;

  return (
    <div style={{ padding: 24 }}>
      <Card title="产值统计" bordered={false}>
        <Space style={{ marginBottom: 16 }}>
          <RangePicker 
            style={{ width: 250 }} 
            onChange={setTimeRange} 
            placeholder={['开始时间', '结束时间']}
          />
          <Select
            style={{ width: 180 }}
            value={projectFilter}
            onChange={setProjectFilter}
            placeholder="选择项目"
          >
            <Option value="all">全部项目</Option>
            <Option value="P2023001">凯泽利总部大楼</Option>
            <Option value="P2023002">未来科技园</Option>
            <Option value="P2023003">城市综合体</Option>
          </Select>
          <Button type="primary" onClick={handleSearch} loading={loading}>
            查询
          </Button>
          <Button icon={<DownloadOutlined />}>导出报表</Button>
        </Space>
        
        <Tabs activeKey={activeTab} onChange={setActiveTab} style={{ marginBottom: 24 }}>
          <TabPane tab="已批准" key="approved">
            <Row gutter={16} style={{ marginBottom: 24 }}>
              <Col span={6}>
                <Card>
                  <Statistic 
                    title="总产值（含税）" 
                    value={totalOutput} 
                    precision={2}
                    prefix="¥"
                    valueStyle={{ color: '#1890ff' }}
                  />
                </Card>
              </Col>
              <Col span={6}>
                <Card>
                  <Statistic 
                    title="总产值（不含税）" 
                    value={totalOutputNoTax} 
                    precision={2}
                    prefix="¥"
                    valueStyle={{ color: '#52c41a' }}
                  />
                </Card>
              </Col>
              <Col span={6}>
                <Card>
                  <Statistic 
                    title="总成本" 
                    value={totalCost} 
                    precision={2}
                    prefix="¥"
                    valueStyle={{ color: '#faad14' }}
                  />
                </Card>
              </Col>
              <Col span={6}>
                <Card>
                  <Statistic 
                    title="平均成本率" 
                    value={avgCostRate} 
                    precision={2}
                    suffix="%"
                    valueStyle={{ color: '#722ed1' }}
                  />
                </Card>
              </Col>
            </Row>
            
            <Table 
              columns={columns} 
              dataSource={approvedData} 
              rowKey="id"
              loading={loading}
              pagination={{ pageSize: 10 }}
              scroll={{ x: 4000 }}
              bordered
            />
          </TabPane>
          
          <TabPane tab="未批准" key="pending">
            <Row gutter={16} style={{ marginBottom: 24 }}>
              <Col span={6}>
                <Card>
                  <Statistic 
                    title="总产值（含税）" 
                    value={totalOutput} 
                    precision={2}
                    prefix="¥"
                    valueStyle={{ color: '#1890ff' }}
                  />
                </Card>
              </Col>
              <Col span={6}>
                <Card>
                  <Statistic 
                    title="总产值（不含税）" 
                    value={totalOutputNoTax} 
                    precision={2}
                    prefix="¥"
                    valueStyle={{ color: '#52c41a' }}
                  />
                </Card>
              </Col>
              <Col span={6}>
                <Card>
                  <Statistic 
                    title="总成本" 
                    value={totalCost} 
                    precision={2}
                    prefix="¥"
                    valueStyle={{ color: '#faad14' }}
                  />
                </Card>
              </Col>
              <Col span={6}>
                <Card>
                  <Statistic 
                    title="平均成本率" 
                    value={avgCostRate} 
                    precision={2}
                    suffix="%"
                    valueStyle={{ color: '#722ed1' }}
                  />
                </Card>
              </Col>
            </Row>
            
            <Table 
              columns={columns} 
              dataSource={pendingData} 
              rowKey="id"
              loading={loading}
              pagination={{ pageSize: 10 }}
              scroll={{ x: 4000 }}
              bordered
            />
          </TabPane>
        </Tabs>
      </Card>

      {/* 批准弹窗 */}
      <Modal
        title="批准产值"
        visible={approvalModalVisible}
        onOk={handleApprovalSubmit}
        onCancel={() => setApprovalModalVisible(false)}
        confirmLoading={loading}
        width={600}
      >
        <Form form={form} layout="vertical">
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="salaryCost"
                label="工资成本"
                rules={[{ required: true, message: '请输入工资成本' }]}
              >
                <InputNumber
                  style={{ width: '100%' }}
                  placeholder="请输入工资成本"
                  formatter={value => `¥ ${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')}
                  parser={value => value.replace(/¥\s?|(,*)/g, '')}
                />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="socialInsurance"
                label="企业社保公积金"
                rules={[{ required: true, message: '请输入企业社保公积金' }]}
              >
                <InputNumber
                  style={{ width: '100%' }}
                  placeholder="请输入企业社保公积金"
                  formatter={value => `¥ ${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')}
                  parser={value => value.replace(/¥\s?|(,*)/g, '')}
                />
              </Form.Item>
            </Col>
          </Row>
          
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="otherFees"
                label="其他费用"
                rules={[{ required: true, message: '请输入其他费用' }]}
              >
                <InputNumber
                  style={{ width: '100%' }}
                  placeholder="请输入其他费用"
                  formatter={value => `¥ ${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')}
                  parser={value => value.replace(/¥\s?|(,*)/g, '')}
                />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="commercialInsurance"
                label="商保"
                rules={[{ required: true, message: '请输入商保' }]}
              >
                <InputNumber
                  style={{ width: '100%' }}
                  placeholder="请输入商保"
                  formatter={value => `¥ ${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')}
                  parser={value => value.replace(/¥\s?|(,*)/g, '')}
                />
              </Form.Item>
            </Col>
          </Row>
          
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="equipmentCost"
                label="设备费用"
                rules={[{ required: true, message: '请输入设备费用' }]}
              >
                <InputNumber
                  style={{ width: '100%' }}
                  placeholder="请输入设备费用"
                  formatter={value => `¥ ${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')}
                  parser={value => value.replace(/¥\s?|(,*)/g, '')}
                />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="compensationAmount"
                label="赔偿金额"
                rules={[{ required: true, message: '请输入赔偿金额' }]}
              >
                <InputNumber
                  style={{ width: '100%' }}
                  placeholder="请输入赔偿金额"
                  formatter={value => `¥ ${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')}
                  parser={value => value.replace(/¥\s?|(,*)/g, '')}
                />
              </Form.Item>
            </Col>
          </Row>
          
          <Form.Item
            name="remarks"
            label="备注"
          >
            <Input.TextArea
              placeholder="请输入备注（选填）"
              rows={3}
            />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
}